package biz.datalk.industrialland.admin.exception;

import biz.datalk.industrialland.common.component.excpetion.GlobalFilterExceptionHandler;
import biz.datalk.industrialland.common.exception.ApplicationException;
import biz.datalk.industrialland.common.exception.DatalkTokenException;
import biz.datalk.industrialland.common.util.ExceptionUtil;
import biz.datalk.industrialland.common.util.ReqErrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tarofang@163.com
 * @date 2022-10-24
 */
@Slf4j
@Component("globalFilterExceptionHandler")
@Order(Ordered.HIGHEST_PRECEDENCE + 999)
public class CustomGlobalFilterExceptionHandler extends GlobalFilterExceptionHandler {

    @Override
    protected void chechExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws ServletException, IOException {
        if (this.checkRequestUriExists(request, response, ex)) {
            Throwable rootCause = ExceptionUtil.getRootCauseWithSelf(ex);
            if (rootCause instanceof DatalkTokenException) {
                DatalkTokenException tex = (DatalkTokenException) rootCause;
                ReqErrUtil.reqApi(response, tex.getCode(), tex.getMessage());
            }
            if (rootCause instanceof ApplicationException) {
                ApplicationException apex = (ApplicationException) rootCause;
                ReqErrUtil.reqApi(response, apex.getCode(), apex.getMessage());
            } else {
                throw new ServletException(ex);
            }
        }
    }

}
